const { LabelUserModel, LabelModel } = require("../model/DataModel");

class LabelUserService {
  async create(data) {
    const { labelId, userId } = data
    const info = await LabelUserModel.findOne({labelId, userId})
    if(info != null) return info
    const res = await LabelUserModel.create({ labelId, userId })
    const label = await LabelModel.findOne({ _id: labelId })
    if (JSON.stringify(res) !== "{}") {
      label.attention_count++
      label.save()
    }
    return res
  }

  // async countUser(id) {
  //   return await LabelUserModel.countDocuments({ _id: id })
  // }

  // async findOne(labelId, userId) {
  //   return await LabelUserModel.findOne({ labelId, userId })
  // }

  async remove(data) {
    const { labelId, userId } = data
    const res =  await LabelUserModel.deleteOne({ labelId, userId })
    const label = await LabelModel.findOne({ _id: labelId })
    if (res.n == 1) {
      label.attention_count--
      label.save()
    }
    return res
  }

  async findByUserId(userId) {
    return await LabelUserModel.find({ userId }, { userId: 0 }).populate('labelId').exec()
  }
}

module.exports = new LabelUserService()